/**
 * 明细分类账记账 - 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0002.KA.KeepDetailMainForm", {
  extend: "PSI.AFX.Form.MainForm",

  config: {
    permission: null
  },

  /**
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      items: [{
        tbar: me.getToolbarCmp(),
        id: me.buildId(me, "panelQueryCmp"),
        region: "north",
        height: 100,
        header: false,
        collapsible: true,
        collapseMode: "mini",
        border: 0,
        layout: {
          type: "table",
          columns: 5
        },
        bodyCls: "PSI-Query-Panel",
        items: me.getQueryCmp()
      }, {
        region: "center",
        layout: "border",
        border: 0,
        ...PSI.Const.BODY_PADDING,
        items: [{
          region: "center",
          layout: "border",
          split: true,
          border: 1,
          items: [{
            region: "center",
            border: 0,
            layout: "fit",
            items: me.getMainGrid()
          }
          ],
        }, {
          region: "west",
          layout: "fit",
          width: 250,
          split: true,
          collapsible: true,
          header: false,
          border: 1,
          items: me.getAccGrid(),
        }]
      }]
    });

    me.callParent(arguments);

    me.editQueryOrg = PCL.getCmp(me.buildId(me, "editQueryOrg"));
    me.editQueryPeriodYear = PCL.getCmp(me.buildId(me, "editQueryPeriodYear"));
    me.editQueryPeriodMonth = PCL.getCmp(me.buildId(me, "editQueryPeriodMonth"));
    me.editQuerySubject = PCL.getCmp(me.buildId(me, "editQuerySubject"));

    me.panelQueryCmp = PCL.getCmp(me.buildId(me, "panelQueryCmp"));

    // AFX: 查询控件input List
    me.__editorList = [
      me.editQueryOrg,
      me.editQueryPeriodYear, me.editQueryPeriodMonth,
      me.editQuerySubject,
    ];


    me._keyMapMain = PCL.create("PCL.util.KeyMap", PCL.getBody(), [{
      key: "Q",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }
        me.editQuerySubject.focus();
      },
      scope: me
    }, {
      key: "H",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        const panel = me.panelQueryCmp;
        if (panel.getCollapsed()) {
          panel.expand();
        } else {
          panel.collapse();
        };
      },
      scope: me
    },
    ]);

    me.queryCompanyList();
  },

  /**
   * @private
   */
  getToolbarCmp() {
    const me = this;

    let result = [];
    let list = [];

    // 记账
    result.push({
      iconCls: "PSI-tb-new",
      text: "把凭证登记到明细账",
      ...PSI.Const.BTN_STYLE,
      scope: me,
      handler: me._onKeepDetail,
    });

    // 关账
    if (result.length > 0) {
      result.push("-");
    }
    result.push({
      text: "关账",
      tooltip: me.buildTooltip("标记明细分类账已经完成记账"),
      ...PSI.Const.BTN_STYLE,
      scope: me,
      handler: me._onCloseDetail,
    }, {
      text: "取消关账",
      tooltip: me.buildTooltip("撤销明细分类账的完成记账标记"),
      ...PSI.Const.BTN_STYLE,
      scope: me,
      handler: me._onCancelCloseDetail,
    });

    // 指南
    // 关闭
    if (result.length > 0) {
      result.push("-");
    }
    result.push({
      iconCls: "PSI-tb-help",
      text: "指南",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        window.open(me.URL("/Home/Help/index?t=accKeepDetail"));
      }
    }, "-", {
      iconCls: "PSI-tb-close",
      text: "关闭",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        me.closeWindow();
      }
    });

    result = result.concat(me.getShortcutCmp());

    return result;
  },

  /**
   * 快捷访问
   * 
   * @private
   */
  getShortcutCmp() {
    return ["->",
      {
        cls: "PSI-Shortcut-Cmp",
        labelWidth: 0,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield",
        width: 90
      }
    ];
  },

  /**
 * 查询条件
 * 
 * @private
 */
  getQueryCmp() {
    const me = this;

    const modelName = me.buildModelName(me, "QueryOrg");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "name"]
    });

    return [{
      xtype: "container",
      height: 26,
      html: `<h2 style='margin-left:20px;margin-top:18px;color:#595959;display:inline-block'>明细分类账记账</h2>
                &nbsp;&nbsp;<span style='color:#8c8c8c'>把已复核的会计凭证登记到明细分类账</span>
                <div style='float:right;display:inline-block;margin:10px 0px 0px 20px;border-left:1px solid #e5e6e8;height:40px'>&nbsp;</div>
                `
    }, {
      id: me.buildId(me, "editQueryOrg"),
      labelWidth: 70,
      width: 490,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "组织机构",
      margin: "10, 0, 0, 0",
      xtype: "combobox",
      queryMode: "local",
      editable: false,
      valueField: "id",
      displayField: "name",
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        },
        select: {
          fn: me._onComboOrgSelect,
          scope: me
        },
      },
      colspan: 4,
    }, { xtype: "container" }, {
      id: me.buildId(me, "editQueryPeriod"),
      labelWidth: 70,
      width: 220,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "会计期间",
      margin: "5, 0, 0, 0",
      xtype: "fieldcontainer",
      layout: "hbox",
      items: [
        {
          xtype: "numberfield",
          hideTrigger: true,
          allowDecimals: false,
          width: 40,
          value: (new Date()).getFullYear(),
          id: me.buildId(me, "editQueryPeriodYear"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, { xtype: "displayfield", value: "年", width: 15, }, {
          xtype: "combobox",
          width: 70,
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [[1, "一月"], [2, "二月"],
            [3, "三月"], [4, "四月"],
            [5, "五月"], [6, "六月"],
            [7, "七月"], [8, "八月"],
            [9, "九月"], [10, "十月"],
            [11, "十一月"], [12, "十二月"]]
          }),
          valueField: "id",
          displayFIeld: "text",
          queryMode: "local",
          editable: false,
          value: (new Date()).getMonth() + 1,
          id: me.buildId(me, "editQueryPeriodMonth"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }
      ],
    }, {
      id: me.buildId(me, "editQuerySubject"),
      labelWidth: 120,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "会计科目码 <span class='PSI-shortcut-DS'>Alt + Q</span>",
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      listeners: {
        specialkey: {
          fn: me.__onLastEditSpecialKey,
          scope: me
        }
      }
    }, {
      xtype: "container",
      colspan: 2,
      items: [{
        xtype: "button",
        text: "查询",
        cls: "PSI-Query-btn1",
        width: 100,
        height: 26,
        margin: "5 0 0 10",
        handler: me._onQuery,
        scope: me
      }, {
        xtype: "button",
        text: "清空查询条件",
        cls: "PSI-Query-btn2",
        width: 100,
        height: 26,
        margin: "5, 0, 0, 10",
        handler: me._onClearQuery,
        scope: me
      }, {
        xtype: "button",
        text: "隐藏工具栏 <span class='PSI-shortcut-DS'>Alt + H</span>",
        cls: "PSI-Query-btn3",
        width: 140,
        height: 26,
        iconCls: "PSI-button-hide",
        margin: "5 0 0 20",
        handler() {
          me.panelQueryCmp.collapse();
        },
        scope: me
      }]
    },];
  },

  /**
   * @private
   */
  getQueryParam() {
    const me = this;

    const result = {};

    return result;
  },

  /**
   * @private
   */
  queryCompanyList() {
    const me = this;
    const store = me.editQueryOrg.getStore();
    const r = {
      url: me.URL("SLN0002/KA/companyList"),
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (data.length > 0) {
            me.editQueryOrg.setValue(data[0]["id"]);

            me.refreshAccGrid();
          }
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  getAccGrid() {
    const me = this;

    if (me._accGrid) {
      return me._accGrid;
    }

    const modelName = me.buildModelName(me, "AccGrid");

    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "accNumber", "name", "subjectCode", "subAccLevel"]
    });

    me._accGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-FC",
      header: false,
      border: 0,
      columnLines: true,
      columns: [{
        header: "账簿码",
        dataIndex: "accNumber",
        menuDisabled: true,
        sortable: false,
        width: 100
      }, {
        header: "账簿名称",
        dataIndex: "name",
        width: 200,
        menuDisabled: true,
        sortable: false,
        renderer(value) {
          return me.toAutoWrap(value);
        }
      },],
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {
        select: {
          fn: me._onAccGridSelect,
          scope: me
        }
      }
    });

    return me._accGrid;
  },

  /**
   * @private
   */
  refreshAccGrid() {
    const me = this;

    me.getMainGrid().getStore().removeAll();

    const companyId = me.editQueryOrg.getValue();
    if (!companyId) {
      return;
    }

    const subjectCode = me.editQuerySubject.getValue();

    const el = PCL.getBody();
    const store = me.getAccGrid().getStore();
    el.mask(PSI.Const.LOADING);
    const r = {
      url: me.URL("SLN0002/KA/queryAccList"),
      params: {
        companyId,
        subjectCode,
      },
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (store.getCount() > 0) {
            me.getAccGrid().getSelectionModel().select(0);
          }
        }

        el.unmask();
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  getMainGrid() {
    const me = this;

    if (me._mainGrid) {
      return me._mainGrid;
    }

    const modelName = me.buildModelName(me, "AccDetailData");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "subject", "debit", "credit", "balance", "balanceDir"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._mainGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-HL",
      viewConfig: {
        enableTextSelection: true
      },
      columnLines: true,
      border: 0,
      columns: {
        defaults: {
          menuDisabled: true,
          sortable: false
        },
        items: [PCL.create("PCL.grid.RowNumberer", {
          text: "#",
          width: 40
        }), {
          header: "科目",
          dataIndex: "subjectCode"
        }]
      },
      store,
    });

    return me._mainGrid;
  },

  /**
   * @private
   */
  reconfigMainGrid() {
    const me = this;

    const fields = [];
    const cols = [PCL.create("PCL.grid.RowNumberer", {
      text: "#",
      width: 40
    })];

    me._fmtCols.forEach((col) => {
      fields.push(col.fieldName);

      const c = {
        dataIndex: col.fieldName,
        header: col.caption,
        width: col.colWidth,
      }

      if (col.fieldName == "acc_db" || col.fieldName == "acc_cr" || col.fieldName == "acc_balance"
        || col.fieldName == "x_db_price" || col.fieldName == "x_cr_price" || col.fieldName == "x_balance_price"
      ) {
        PCL.apply(c, {
          align: "right",
          renderer(value) {
            return me.formatMoney(value);
          }
        });
      }

      if (col.fieldName == "x_db_cnt" || col.fieldName == "x_cr_cnt" || col.fieldName == "x_balance_cnt") {
        PCL.apply(c, {
          align: "right",
        });
      }

      cols.push(c);
    });

    const modelName = me.buildModelName(me, "AccDetailData");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields,
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me.getMainGrid().reconfigure(store, cols);
  },

  /**
   * @private
   */
  queryAccDetailData() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    const subjectCode = me._selectedSubjectCode;
    const year = me.editQueryPeriodYear.getValue();
    const month = me.editQueryPeriodMonth.getValue();

    const item = me.getAccGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }
    const subAccLevel = parseInt(item[0].get("subAccLevel"));
    const grid = me.getMainGrid();
    const el = grid.getEl();
    el?.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0002/KA/queryDataForDetailAcc"),
      params: {
        companyId,
        subjectCode,
        year,
        month,
        subAccLevel,
      },
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
        }

        el?.unmask();
      }
    });
  },

  /**
   * @private
   */
  _onComboOrgSelect() {
    const me = this;

    me.refreshAccGrid();
  },

  /**
   * @private
   */
  _onQuery() {
    const me = this;

    me.refreshAccGrid();
  },

  /**
   * @private
   */
  _onClearQuery() {
    const me = this;

    me.editQuerySubject.setValue(null);

    me._onQuery.apply(me, []);
  },

  /**
   * @private
   */
  _onAccGridSelect() {
    const me = this;
    const companyId = me.editQueryOrg.getValue();

    const item = me.getAccGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }
    const subjectCode = item[0].get("subjectCode");

    const grid = me.getMainGrid();
    const el = grid.getEl();
    el?.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0002/KA/queryFmtColsForDetailAcc"),
      params: {
        companyId,
        subjectCode,
      },
      callback(options, success, response) {
        el?.unmask();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          me._fmtCols = data;
          me._selectedSubjectCode = subjectCode;

          me.reconfigMainGrid();
          me.queryAccDetailData();
        }
      }
    });
  },

  /**
   * @private
   */
  _onKeepDetail() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    if (!companyId) {
      me.showInfo("请选择组织机构");
      return;
    }

    const store = me.editQueryOrg.getStore();
    const org = store.getById(companyId);
    let name = org?.get("name");
    if (!name) {
      name = "";
    }

    const info = `当前组织机构：<span style='color:red'>${name}</span>
                  <br/>
                  请确认是否登记明细账？`;

    const funcConfirm = () => {
      const el = PCL.getBody();
      el.mask("正在记账中...");
      const r = {
        url: me.URL("SLN0002/KA/keepDetail"),
        params: {
          companyId,
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.tip("成功完成明细账记账操作", true);
              me.queryAccDetailData();
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };

    me.confirm(info, funcConfirm);
  },

  /**
   * @private
   */
  _onCloseDetail() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    if (!companyId) {
      me.showInfo("请选择组织机构");
      return;
    }

    const store = me.editQueryOrg.getStore();
    const org = store.getById(companyId);
    let name = org?.get("name");
    if (!name) {
      name = "";
    }

    const info = `当前组织机构：<span style='color:red'>${name}</span>
                  <br/>
                  请确认是否关账？`;

    const funcConfirm = () => {
      const el = PCL.getBody();
      el.mask("正在关账中...");
      const r = {
        url: me.URL("SLN0002/KA/closeAccDetail"),
        params: {
          companyId,
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.showInfo("成功完成关账操作");
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };

    me.confirm(info, funcConfirm);
  },

  /**
   * @private
   */
  _onCancelCloseDetail() {
    const me = this;

    const companyId = me.editQueryOrg.getValue();
    if (!companyId) {
      me.showInfo("请选择组织机构");
      return;
    }

    const store = me.editQueryOrg.getStore();
    const org = store.getById(companyId);
    let name = org?.get("name");
    if (!name) {
      name = "";
    }

    const info = `当前组织机构：<span style='color:red'>${name}</span>
                  <br/>
                  请确认是否取消关账？`;

    const funcConfirm = () => {
      const el = PCL.getBody();
      el.mask("正在取消关账中...");
      const r = {
        url: me.URL("SLN0002/KA/cancelCloseAccDetail"),
        params: {
          companyId,
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.showInfo("成功取消关账操作");
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };

    me.confirm(info, funcConfirm);
  },
});
